// Modbus
var PageModbus = {
    id: "PageModbus", //页面id
    menu: "i18n.lan.menu.modbus", //所属菜单(一级菜单名)
    title: "i18n.lan.menu.PageModbus", //标题（二级菜单名）
    parentIcon: "icon-me-register", //图标
    icon: "icon-me-register", //图标
    refreshBtnCmd: "MODBUS_DUMPS", //刷新按钮指令
    saveBtn: true, //保存按钮
    content: "test", //页面内容
    el: [ //控件
        {//样式
            elname:"style",
            text:"#PageModbus>label{min-width:150px}",//调整文本框前面文字的宽度
        },
        {
            elname: "checkbox",
            id:"modbus_modbusEnable",
            label: i18n.lan.PageModbus.modbusEnable,
            endRow: true,
            attrs: {
                dumpKey: "MODBUS_MASTER_ENABLED",
                cmdKey: "MODBUSMASTEREN"
            },
        },
        {
            elname: "checkbox",
            id:"modbus_autoReadMulti",
            label: i18n.lan.PageModbus.autoReadMulti,
            endRow: true,
            attrs: {
                dumpKey: "MODBUS_MULTI_READ_ENABLED",
                cmdKey: "MODBUSMULTIREAD"
            },
        },
        {
            elname: "text",
            label: i18n.lan.PageModbus.readDelay,
            endRow: true,
            attrs: {
                dumpKey: "MODBUSREADDLY",
                cmdKey: "MODBUSREADDELAY"
            },
        },
        {
            elname: "text",
            label: i18n.lan.PageModbus.responseTo,
            endRow: true,
            attrs: {
                dumpKey: "MODBUSRESPTO",
                cmdKey: "MODBUSRESPONSETO"
            },
        },
        {
            elname: "text",
            label: i18n.lan.PageModbus.connTimeout,
            endRow: true,
            attrs: {
                dumpKey: "MODBUSDISCONNTO",
                cmdKey: "MODBUSDISCONNECTTO"
            },
        },
        // modbus 查询间隔（跳过，同轮询间隔有点区别，暂不使用）
        // ModbusQueryInterval
        // lora 查询一次后延迟多长时间进行下一次查询（暂不使用）
        // ModbusLoraQueryDelay
        {
            elname: "datagrid",
            rowCount: Device.getNodesCount("reg"), //必选,行数
            data: {
                height: "280px",
                // onEndEdit: PageModbus_onEndEdit,
                frozenColumns: [
                    [ //表格列,field为列标题
                        {
                            field: "index",
                            title: i18n.lan.common.index,
                            width: 40,
                            align: "center",
                        },
                    ]
                ],
                columns: [
                    [ //表格列,field为列标题
                        {
                            field: "value",
                            dumpKey: "MREG<n>STATE",
                            dumpParamIndex: 1,
                            width: 70,
                        },
                        {
                            field: "name",
                            editor: Easyui.editor.textbox,
                            dumpKey: "MREG<n>NAME",
                            dumpParamIndex: 0,
                            transcode: "true",
                            cmdKey: "MODBUSREG<n>NAME",
                            otherFields: "unit",
                            width: 100,
                        },
                        {
                            field: "unit",
                            editor: Easyui.editor.textbox,
                            dumpKey: "MREG<n>NAME",
                            dumpParamIndex: 1,
                            transcode: "true",
                            width: 60,
                        },
                        {
                            field: "salveAddress",
                            formatter: function (value, index) {
                                return dealModbusMultiAddress(value, index, 'salveAddress');
                            },
                            editor: Easyui.editor.textbox,//不使用numberbox是为了可以快速设置
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 0,
                            cmdKey: "MODBUSREG<n>SET",
                            //TODO:修改参数
                            getValue: "getModbusRegSetCmd(rows[row].index)", //自定义获取指令的方法,row是行号
                            width: 70,
                        },
                        {
                            field: "registerAddress",
                            formatter: function (value, index) {
                                return dealModbusMultiAddress(value, index, 'registerAddress');
                            },
                            editor: Easyui.editor.textbox,//不使用numberbox是为了可以快速设置
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 1,
                            width: 80,
                        },
                        {
                            field: "registerType",
                            formatter: Easyui.formatter.combobox,
                            editor: new Easyui.editor.Combobox(i18n.lan.PageModbus.registerTypeItemsKV),
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 2,
                            width: 120,
                        },
                        {
                            field: "driverType",
                            formatter: Easyui.formatter.combobox,
                            editor: new Easyui.editor.Combobox(i18n.lan.PageModbus.driverTypeItemsKV),
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 3,
                            width: 120,
                        },
                        {
                            field: "ioNoramlState",
                            formatter: Easyui.formatter.combobox,
                            editor: new Easyui.editor.Combobox(i18n.lan.PageModbus.nsItemsKV),
                            dumpKey: "MREG<n>NODE_NS",
                            cmdKey: "MODBUSREG<n>NS",
                            width: 120,
                        },
                        {
                            field: "value32bit",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(1,value)", //value是刷新出来的值
                            width: 60,
                            align: "center",
                        },
                        {
                            field: "wordInverse",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(2,value)",
                            align: "center",
                        },
                        {
                            field: "floatValue",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(4,value)",
                            width: 60,
                            align: "center",
                        },
                        {
                            field: "unsignedValue",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(8,value)",
                            width: 70,
                            align: "center",
                        },
                        {
                            field: "byteInverse",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(16,value)",
                            width: 70,
                            align: "center",
                        },
                        {
                            field: "maskAlarm",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(32,value)",
                            align: "center",
                        },                        
                        {
                            field: "maskNormal",
                            editor: {
                                type: "checkbox",
                                options: {
                                    on: "1",
                                    off: "0"
                                }
                            },
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(64,value)",
                            width: 60,
                            align: "center",
                        },
                        {
                            field: "value16bit",
                            formatter:Easyui.formatter.checkbox,
                            editor: Easyui.editor.checkbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 4,
                            dealDumpParam: "dealRegFlag(128,value)",
                            width: 60,
                            align: "center",
                        },
                        {
                            field: "maskValue",
                            editor: Easyui.editor.numberbox,
                            dumpKey: "MREG<n>SET",
                            dumpParamIndex: 5,
                            width: 60,
                        },
                        {
                            field: "adjValue",
                            editor: Easyui.editor.numberbox4,
                            dumpKey: "MREG<n>NODE_RANGE1",
                            dumpParamIndex: 3,
                            cmdKey: "MODBUSREG<n>ADJ",
                            width: 60,
                        },
                        {
                            field: "scaleValue",
                            editor: Easyui.editor.numberbox4,
                            dumpKey: "MREG<n>NODE_RANGE1",
                            dumpParamIndex: 4,
                            cmdKey: "MODBUSREG<n>SCALE",
                            width: 60,
                        },
                        /*
                        {//计算公式类型
                            field: "formType",
                            formatter: Easyui.formatter.combobox,
                            editor: new Easyui.editor.Combobox(i18n.lan.PageModbus.formTypeItemsKV,true,setDefaultKValue),
                            dumpKey: "MREG<n>FORM",
                            dumpParamIndex:0,
                            cmdKey: "MODBUSREG<n>FORM",
                            otherFields:"formKValue,formDefaultValue",
                            width: 120,
                        },
                        {//公式k值
                            field: "formKValue",
                            editor: {
                                type: 'numberbox',
                                options: {
                                    precision: 9
                                }
                            },
                            dumpKey: "MREG<n>FORM",
                            dumpParamIndex:1,
                            width: 100,
                        },
                        {//公式初值f0
                            field: "formDefaultValue",
                            editor: {
                                type: 'numberbox',
                                options: {
                                    precision: 6
                                }
                            },
                            dumpKey: "MREG<n>FORM",
                            dumpParamIndex:2,
                            width: 100,
                        },
                        {
                            field: "mapAdjId",
                            formatter: Easyui.formatter.combobox,
                            editor: new Easyui.editor.Combobox(i18n.lan.PageModbus.mapIdItems),
                            dumpKey: "MREG<n>NODE_MAP",
                            dumpParamIndex: 2,
                            cmdKey: "MODBUSREG<n>MAPADJID",
                            width: 120,
                        },
                        {
                            field: "mapAdjCh",
                            editor: Easyui.editor.textbox,
                            dumpKey: "MREG<n>NODE_MAP",
                            dumpParamIndex: 3,
                            cmdKey: "MODBUSREG<n>MAPADJCH",
                            width: 130,
                        },*/
                    ]
                ],
            }
        },
        {
            elname: "span",
            text: i18n.lan.PageModbus.copy,
            attrs: {
                style: "display:inline-block;width:90px;",
            }
        },
        {
            elname: "combobox",
            id: "PageModbus_copyType",
            items: "i18n.lan.PageModbus.copyItmes",
        },
        {
            elname: "span",
            text: i18n.lan.PageModbus.startIndex,
            attrs: {
                style: "display:inline-block;margin-left:20px;width:60px;",
            }
        },
        {
            elname: "combobox",
            id: "PageModbus_startIndex",
            items: "Device.getRegIndexItems()",
        },
        {
            elname: "span",
            text: i18n.lan.PageModbus.count,
            attrs: {
                style: "display:inline-block;margin-left:20px;width:30px;",
            }
        },
        {
            elname: "combobox",
            id: "PageModbus_count",
            items: "Device.getRegIndexItems()",
        },
        {
            elname: "button",
            text: i18n.lan.PageModbus.ok,
            attrs: {
                onclick: "PageModbus_copy()",
                class: "smallBtn",
            }
        },
    ],
}
CmdPage.add(PageModbus); //添加到页面管理

//寄存器值类型处理方法; enableNum:代表启用的值(2进制位为1时的10进制值),value是刷新出的值
function dealRegFlag(enableNum, value) {
    try {
        value = parseInt(value);
        value &= enableNum;
    } catch (err) {}
    return value > 0 ? "1" : "0";
}

//获得modbus参数设置指令
function getModbusRegSetCmd(rowIndex) {
    let value = "";
    let row = PageModbus.dgData.rows[rowIndex];
    //参数
    // modbusreg0set1(从机地址),2(寄存器地址),1(寄存器类型),0(驱动类型),0(值类型开关),4(掩码)
    let paramFields = ["salveAddress", "registerAddress", "registerType", "driverType"];
    //值类型开关()
    let regValTypeFileds = ["value32bit", "wordInverse", "floatValue", "unsignedValue", "byteInverse", "maskAlarm", "maskNormal", "value16bit"];
    //前面的参数
    for (let i in paramFields) {
        value += row[paramFields[i]];
        value += ",";
    }
    //组合值类型开关为1个参数
    let val2 = 0;
    for (let bit in regValTypeFileds) {
        val2 += row[regValTypeFileds[bit]] << bit;
    }
    value += row["maskValue"];//掩码
    value += ",";
    value += val2.toString(16);
    
    return value;
}

//编辑结束事件
function PageModbus_onEndEdit(index, row) {
    // DatagridTool.onEndEdit(index,row);//默认的处理方法
    // alert(row.salveAddress);
}
//允许自动复制地址
function dealModbusMultiAddress(value, row, field) {
    let multiRegex = new RegExp("^([0-9]+)\\*([0-9]*)$"); //多个相同的地址
    let addRegex = new RegExp("^([0-9]+)\\+([0-9]*)$"); //加1的地址
    let add2Regex = new RegExp("^([0-9]+)\\+\\+([0-9]*)$"); //加2的地址
    let vals;
    let copy = false; //是否复制
    let addNum = 0; //自动增加的数字
    let copyCount = PageModbus.dgData.rows.length;

    if (multiRegex.test(value)) {
        vals = multiRegex.exec(value);
        copy = true;
    } else if (addRegex.test(value)) {
        vals = addRegex.exec(value);
        copy = true;
        addNum = 1;
    } else if (add2Regex.test(value)) {
        vals = add2Regex.exec(value);
        copy = true;
        addNum = 2;
    }
    if (copy) {
        //输入位置的值
        value = parseInt(vals[1]);
        row[field] = value;
        //复制的值
        copyCount = vals.length > 2 ? copyCount = parseInt(vals[2]) : copyCount;
        for (let i = 0; i < copyCount && (row.index + i) < PageModbus.dgData.rows.length; i++) {
            PageModbus.dgData.rows[row.index + i][field] = value + i * addNum;
            PageModbus.dgData.rows[row.index + i].registerType = row.registerType; //默认复制寄存器类型
            DatagridTool.addToUpdatedRows("PageModbus_dg", PageModbus.dgData.rows[row.index + i]);
        }
        DatagridTool.updateData("PageModbus_dg", true);
    }
    value = parseInt(value);
    value = isNaN(value) ? 0 : value;
    return value;
}

//复制寄存器或从机
function PageModbus_copy() {
    let flag = $("#PageModbus_copyType").val();
    let start = $("#PageModbus_startIndex").val();
    let count = $("#PageModbus_count").val();
    let cmd = "MODBUSREG{0}COPY{1}{2}".format(start ? start : 0, flag, count ? count : 0);
    sendCmds([cmd, "MODBUS_DUMPS"]);
}
//设置公式默认参数(K)
function setDefaultKValue(newVal,oldVal){
    let selectIndex = $('#PageModbus_dg').datagrid('getSelected').index;
    //获取相对应的editor
    let ed = $('#PageModbus_dg').datagrid('getEditor',{index:selectIndex,field:'formKValue'});
    switch(newVal){
        case 1:
            ed.target.textbox('setValue',1.984E-5);//textbox赋值方法
            break;
        default:
            if(ed.target.textbox('getValue')==1.984E-5){
                ed.target.textbox('setValue',0);
            }
            break;
    }
}